package com.qf.fmw.filter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter extends BaseFilter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException, ServletException {
        //1.转换请求和响应的对象
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //2.解决乱码问题
        //解决 post 请求乱码问题
        request.setCharacterEncoding("utf-8");
        //解决响应乱码问题
        response.setContentType("text/html;charset=utf-8");

        //3.判断请求哪些在未登录前可以直接放行
        String uri = request.getRequestURI();//获取请求地址
        String type = request.getParameter("type");
        if(uri.endsWith("login.jsp")
                || uri.endsWith("register.jsp")
                || uri.endsWith("CodeServlet")
                || "login".equals(type)
                || "register".equals(type)){
            filterChain.doFilter(request,response);
            return;
        }

        //4.判断是否有登录
        Object id = request.getSession().getAttribute("id");
        if(id != null){
            filterChain.doFilter(request,response);
            return;
        }

        //5.重定向到登录页面
        //response.sendRedirect("login.jsp");
        response.getWriter().write("<script>alert('请先登录');location.href='login.jsp'</script>");
    }

}
